<?php
/**
 * Created by PhpStorm.
 * User: Da Xiong
 * Date: 2019/1/24
 * Time: 14:41
 */

namespace App\HttpController\Admin;


use App\Model\ConfigModel;

class Config extends Auth
{

    /**
     * 获取配置信息
     * @return bool|void
     * @throws \EasySwoole\Mysqli\Exceptions\ConnectFail
     * @throws \EasySwoole\Mysqli\Exceptions\PrepareQueryFail
     * @throws \Throwable
     */
    public function index(){
        $configModel = new ConfigModel();
        $result = $configModel->getAll();
        return $this->writeJson(0,$result);
    }

    /**
     * 更新配置信息
     * @return bool
     * @throws \EasySwoole\Mysqli\Exceptions\ConnectFail
     * @throws \EasySwoole\Mysqli\Exceptions\PrepareQueryFail
     * @throws \Throwable
     */
    public function update(){
        $request = $this->request();
        $param = $request->getRequestParam();
        if(isset($param['id']) && $param['id'] > 0){
            // 更新
            $configModel = new ConfigModel();
            $find = $configModel->find($param['id']);
            if(!$find){
                return $this->writeJson(1,null,'error');
            }
            $result = $configModel->update($param);
            if($result){
                // 更新成功
                return $this->writeJson(0);
            }else{
                // 更新失败
                return $this->writeJson(1,null,'error1');
            }
        }else{
            // 新增
            $configModel = new ConfigModel();
            if(!isset($param['name']) || $param['name'] == ''){
                return $this->writeJson(1,null,'error2');
            }
            $find = $configModel->where('name',$param['name'])->first();
            if($find){
                return $this->writeJson(1,null,'name 已存在');
            }
            $result = ConfigModel::create($param);
            if($result){
                // 新增成功
                return $this->writeJson(0);
            }else{
                // 新增失败
                return $this->writeJson(1,null,'error3');
            }
        }
    }
}

